package com.cgbl.cg.vm.mine

import android.app.Application
import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import api.CourseServiceFactory
import api.ShopServiceFactory
import com.alibaba.fastjson.JSON
import com.cgbl.cg.utils.city.BeanTransferHelper
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.model.CommentBean
import com.robot.base.model.CourseInfoBean
import com.robot.base.model.PageListBean
import com.robot.base.util.ToastUtils
import com.robot.base.util.arouter.ARouterUtil
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse

class CourseProfileViewModel(application: Application) : GLBaseViewModel(application) {

    var productId = ""

    var accountId = ""

    val uc = UiChangeEvent()

    val tabType = ObservableInt(TAB_PROFILE)

    var isCollectionField = ObservableBoolean(false)

    var isBuyField = ObservableBoolean(false)


    var bottomRightBtn = ObservableField("立即购买")

    var commentTagField = ObservableField<String>()

    var id = ""

    var isFirs = true


    val clickFullScreenCommand = BindingCommand<Any>(BindingAction {
        ARouterUtil.goToActivity(AppConstants.Router.Main.A_VIDEO)
    })
    val addCartCommand = BindingCommand<Any>(BindingAction {
        if (isBuyField.get()) {
            //查看购物车
            ARouterUtil.goToActivity(AppConstants.Router.Mine.A_MINE_SHOPPING_CAR)
            return@BindingAction
        }
        doAddCart()
    })

    val buyCommand = BindingCommand<Any>(BindingAction {
        if (isBuyField.get()) {
            return@BindingAction
        }
        if (TextUtils.isEmpty(productId)) {
            ToastUtils.showShort("商品为空!")
            return@BindingAction
        }
        ARouterUtil.goToActivityWithBundle(AppConstants.Router.Mine.A_MINE_CONFIRM_ORDER,
            Bundle().apply {
                putString(
                    AppConstants.BundleKey.SHOP_CART_BEAN, JSON.toJSONString(
                        BeanTransferHelper.createConfirmOrderProductByCourse(productId, "1")
                    )
                )
            })
    })

    val addCollectionCommand = BindingCommand<Any>(BindingAction {
        doCollection()
    })

    val toCommentProfileCommand = BindingCommand<Any>(BindingAction {
        toComment()
    })
    val clickSelectProfileCommand = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_PROFILE)
        uc.switchTabEvent.postValue(tabType.get())
    })

    val clickSelectDirectoryCommand = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_DIRECTORY)
        uc.switchTabEvent.postValue(tabType.get())
    })

    val clickSelectCommentCommand = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_COMMENT)
        uc.switchTabEvent.postValue(tabType.get())
    })

    val clickSelectFileCommand = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_FILE)
        uc.switchTabEvent.postValue(tabType.get())
    })

    val clickShoppingCarCommand = BindingCommand<Any>(BindingAction {
        ARouterUtil.goToActivity(AppConstants.Router.Mine.A_MINE_SHOPPING_CAR)
    })

    val userAvatar = ObservableField<String>()

    var page = 1

    var pageSize = 10

    init {
        userAvatar.set("https://ep.watsons.com.cn/MPOSImage/3456_sco_home_pic.png")
    }

    class UiChangeEvent {

        val switchTabEvent: SingleLiveEvent<Int> = SingleLiveEvent()

        val courseInfoData: SingleLiveEvent<CourseInfoBean> = SingleLiveEvent()

        val refreshCommentEvent: SingleLiveEvent<List<CommentBean>> = SingleLiveEvent()

        val loadMoreCommentEvent: SingleLiveEvent<List<CommentBean>> = SingleLiveEvent()

    }

    fun refresh() {
        page = 1
        fetchCourseComment(productId)
    }

    fun loadMore() {
        page++
        fetchCourseComment(productId)
    }

    fun fetchCourseInfo(id: String, comment: Boolean? = false) {
        CourseServiceFactory.getCourseInfo(mapOf("id" to id))
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<CourseInfoBean>>(this) {
                override fun onNext(t: BaseResponse<CourseInfoBean>) {
                    if (comment == true) {
                        commentTagField.set("评价（${t.data.commentCount}）")
                    } else {
                        productId = t.data.id ?: ""
                        accountId = t.data.accountId ?: ""

                        isCollectionField.set(t.data.collectType == "1")
                        commentTagField.set("评价（${t.data.commentCount}）")
                        val ispay = t.data.pay

                        isBuyField.set(t.data.pay == "1")
                        uc.courseInfoData.postValue(t.data)
//                        if(isFirs){
//                            isBuyField.set(false)
//                            isFirs = false
//                        }
                        bottomRightBtn.set(if (isBuyField.get()) "立即学习" else " 立即购买")

                    }
                }
            })
    }

    fun fetchCourseComment(id: String) {
        productId = id
        val params = mapOf(
            "allOff" to "1",
            "type" to "0",
            "courseId" to id,
            "pageNo" to page,
            "pageSize" to pageSize
        )
        CourseServiceFactory.pageComment(params).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<PageListBean<CommentBean>>>(this) {
            override fun onNext(t: BaseResponse<PageListBean<CommentBean>>) {
                if (page == 1) {
                    uc.refreshCommentEvent.postValue(t.data.list)
                } else {
                    uc.loadMoreCommentEvent.postValue(t.data.list)
                }
            }
        })
    }

    private fun toComment() {
        if (TextUtils.isEmpty(productId)) {
            ToastUtils.showShort("商品id不能为空！")
            return
        }
        ARouterUtil.goToActivityWithBundle(
            AppConstants.Router.Mine.A_MINE_COMMENT_PROFILE,
            Bundle().apply {
                putInt(
                    AppConstants.BundleKey.COMMENT_PRODUCT_TYPE,
                    AppConstants.BundleValue.COMMENT_TYPE_COURSE
                )
                putString(AppConstants.BundleKey.COMMENT_PRODUCT_ID, productId)
                putString(AppConstants.BundleKey.COMMENT_PARENT_ID, "0")
                putString(AppConstants.BundleKey.COMMENT_ACCOUNT_ID, accountId)
            })
    }

    private fun doAddCart() {
        if (TextUtils.isEmpty(productId)) {
            ToastUtils.showShort("添加失败,商品id不能为空！")
            return
        }
        val params = mapOf("productId" to productId, "type" to "1")

        ShopServiceFactory.cartCreate(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<Any>>(this) {
                override fun onNext(t: BaseResponse<Any>) {
                    ToastUtils.showShort("添加成功!")
                }
            })
    }

    private fun doCollection() {
        if (TextUtils.isEmpty(productId)) {
            ToastUtils.showShort("添加失败,商品id不能为空！")
            return
        }
        val collectType = if (isCollectionField.get()) {
            "0"
        } else {
            "1"
        }
        val params = mapOf("courseId" to productId, "type" to collectType)

        ShopServiceFactory.saveCollectCourse(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<Any>>(this) {
                override fun onNext(t: BaseResponse<Any>) {
                    ToastUtils.showShort(if (collectType == "0") "取消收藏!" else "收藏成功!")
                    isCollectionField.set(collectType == "1")
                }
            })
    }

    fun likeComment(id: String, success: (uploadBean: String) -> Unit) {
        CourseServiceFactory.createCommentLike(
            mapOf(
                "commentId" to id
            )
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
            override fun onNext(t: BaseResponse<String>) {
                success.invoke(t.data)
            }
        })
    }

    companion object {

        const val TAB_PROFILE = 1

        const val TAB_DIRECTORY = 2

        const val TAB_COMMENT = 3

        const val TAB_FILE = 4

    }
}